/**
 * file-list.js - 文件列表处理功能
 * 使用卡片式布局展示文件
 */

class FileListManager {
    constructor() {
        this.files = [];
        this.currentView = 'grid'; // grid or list
        this.initEventListeners();
        this.initUploadHandlers();
    }

    initEventListeners() {
        // 视图切换
        $('#viewToggle').on('click', () => this.toggleView());
        
        // 搜索
        $('#fileSearchInput').on('input', debounce(() => this.filterFiles(), 300));
        
        // 排序
        $('#sortDropdown').on('change', () => this.sortFiles());
        
        // 文件操作
        $(document).on('click', '.file-action', (e) => {
            const action = $(e.currentTarget).data('action');
            const filename = $(e.currentTarget).closest('[data-filename]').data('filename');
            this.handleFileAction(action, filename);
        });
    }

    initUploadHandlers() {
        // 文件选择上传
        $('#fileInput').on('change', (e) => {
            const files = e.target.files;
            if (files && files.length > 0) {
                this.uploadFiles(files);
                // 清空input，允许重复选择相同文件
                e.target.value = '';
            }
        });

        // 拖拽上传
        const container = $('#fileContainer');
        
        container.on('dragover', (e) => {
            e.preventDefault();
            e.stopPropagation();
            container.addClass('drag-over');
        });

        container.on('dragleave', (e) => {
            e.preventDefault();
            e.stopPropagation();
            container.removeClass('drag-over');
        });

        container.on('drop', (e) => {
            e.preventDefault();
            e.stopPropagation();
            container.removeClass('drag-over');
            
            const files = e.originalEvent.dataTransfer.files;
            if (files && files.length > 0) {
                this.uploadFiles(files);
            }
        });
    }

    loadFiles() {
        showLoading();
    $.ajax({
        url: '/api/files/advanced',
            method: 'GET',
        data: {
            search: $('#fileSearchInput').val(),
                sortBy: this.getSortField(),
                order: this.getSortOrder()
            },
            success: (response) => {
                hideLoading();
                if (response.success && Array.isArray(response.files)) {
                    this.files = response.files;
                    this.renderFiles();
                } else {
                    showError('加载文件失败');
                }
            },
            error: () => {
                hideLoading();
                showError('网络错误，请重试');
        }
    });
}

    renderFiles() {
        const container = $('#fileContainer');
        container.empty();

        if (this.files.length === 0) {
            container.html(this.getEmptyTemplate());
            return;
        }

        const template = this.currentView === 'grid' ? this.getGridTemplate() : this.getListTemplate();
        const html = this.files.map(file => template(file)).join('');
        container.html(html);

        // 初始化工具提示
        $('[data-bs-toggle="tooltip"]').tooltip();
    }

    getEmptyTemplate() {
        return `
            <div class="text-center p-5">
                <div class="empty-state">
                    <i class="bi bi-cloud-upload fs-1 text-muted mb-3"></i>
                    <h5>还没有文件</h5>
                    <p class="text-muted">点击上方的上传按钮或拖拽文件到此处开始上传</p>
                </div>
            </div>
        `;
    }

    getGridTemplate() {
        return (file) => `
            <div class="file-card" data-filename="${file.key}">
                <div class="file-preview">
                    ${this.getFilePreview(file)}
                </div>
                <div class="file-info">
                    <div class="file-name" title="${file.key}">${file.key}</div>
                    <div class="file-meta">
                        <span>${this.formatFileSize(file.size)}</span>
                        <span>${this.formatDate(file.putTime * 1000)}</span>
                    </div>
                </div>
                <div class="file-actions">
                    <button class="btn btn-icon file-action" data-action="details" data-filename="${file.key}" data-bs-toggle="tooltip" title="详情">
                        <i class="bi bi-info-circle"></i>
                    </button>
                    <button class="btn btn-icon file-action" data-action="download" data-filename="${file.key}" data-bs-toggle="tooltip" title="下载">
                        <i class="bi bi-download"></i>
                    </button>
                    <button class="btn btn-icon file-action" data-action="share" data-filename="${file.key}" data-bs-toggle="tooltip" title="分享">
                        <i class="bi bi-share"></i>
                    </button>
                    <button class="btn btn-icon file-action" data-action="delete" data-filename="${file.key}" data-bs-toggle="tooltip" title="删除">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }

    getListTemplate() {
        return (file) => `
            <div class="file-row" data-filename="${file.key}">
                <div class="file-icon">
                    ${this.getFileTypeIcon(file.mimeType)}
                </div>
                <div class="file-details">
                    <div class="file-name">${file.key}</div>
                    <div class="file-meta">
                        <span>${this.formatFileSize(file.size)}</span>
                        <span>${file.mimeType}</span>
                        <span>${this.formatDate(file.putTime * 1000)}</span>
                    </div>
                </div>
                <div class="file-actions">
                    <button class="btn btn-sm btn-outline-secondary file-action" data-action="details" data-filename="${file.key}">
                        <i class="bi bi-info-circle"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-primary file-action" data-action="download" data-filename="${file.key}">
                        <i class="bi bi-download"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-info file-action" data-action="share" data-filename="${file.key}">
                        <i class="bi bi-share"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger file-action" data-action="delete" data-filename="${file.key}">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }

    getFilePreview(file) {
        if (file.mimeType && file.mimeType.startsWith('image/')) {
            return `<img src="${file.url}" alt="${file.key}" class="file-thumbnail" onerror="this.onerror=null; this.src='/images/image-error.png';">`;
        }
        return this.getFileTypeIcon(file.mimeType);
    }

    getFileTypeIcon(mimeType) {
        const iconMap = {
            'image': 'bi-file-image',
            'video': 'bi-file-play',
            'audio': 'bi-file-music',
            'pdf': 'bi-file-pdf',
            'word': 'bi-file-word',
            'excel': 'bi-file-excel',
            'powerpoint': 'bi-file-ppt',
            'zip': 'bi-file-zip',
            'text': 'bi-file-text'
        };

        const type = Object.keys(iconMap).find(key => mimeType?.includes(key));
        const iconClass = type ? iconMap[type] : 'bi-file-earmark';
        
        return `<i class="bi ${iconClass}"></i>`;
    }

    handleFileAction(action, filename) {
        switch (action) {
            case 'details':
                showFileDetails(filename);
                break;
            case 'download':
                this.downloadFile(filename);
                break;
            case 'share':
                this.showShareDialog(filename);
                break;
            case 'delete':
                this.deleteFile(filename);
                break;
        }
    }

    downloadFile(filename) {
        // 直接使用下载链接
        window.location.href = `/download?fileName=${encodeURIComponent(filename)}`;
    }

    deleteFile(filename) {
        if (confirm('确定要删除此文件吗？')) {
            $.ajax({
                url: `/delete?fileName=${encodeURIComponent(filename)}`,
                method: 'DELETE',
                success: (response) => {
                    if (response.success) {
                        this.loadFiles();
                        showSuccess('文件已删除');
                    } else {
                        showError('删除失败');
                    }
                }
            });
        }
    }

    toggleView() {
        this.currentView = this.currentView === 'grid' ? 'list' : 'grid';
        $('#viewToggle').find('i').toggleClass('bi-grid bi-list');
        this.renderFiles();
    }

    filterFiles() {
        this.loadFiles();
    }

    sortFiles() {
        this.loadFiles();
    }

    getSortField() {
        const sortValue = $('#sortDropdown').val();
        return sortValue.split('-')[0];
    }

    getSortOrder() {
        const sortValue = $('#sortDropdown').val();
        return sortValue.split('-')[1];
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    formatDate(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    uploadFiles(files) {
        showLoading();
        let completed = 0;
        let failed = 0;
        const total = files.length;

        const updateStatus = () => {
            if (completed === total) {
                hideLoading();
                const successCount = total - failed;
                if (successCount > 0) {
                    showSuccess(`成功上传 ${successCount} 个文件`);
                    this.loadFiles(); // 刷新文件列表
                }
                if (failed > 0) {
                    showError(`${failed} 个文件上传失败`);
                }
            }
        };

        Array.from(files).forEach(file => {
            const formData = new FormData();
            formData.append('file', file);

            $.ajax({
                url: '/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: (response) => {
                    completed++;
                    if (!response.success) {
                        failed++;
                        showError(`文件 ${file.name} 上传失败: ${response.message}`);
                    }
                    updateStatus();
                },
                error: (xhr, status, error) => {
                    completed++;
                    failed++;
                    showError(`文件 ${file.name} 上传失败: ${error}`);
                    updateStatus();
                }
            });
        });
    }

    showShareDialog(filename) {
        $.ajax({
            url: `/api/file/share?fileName=${encodeURIComponent(filename)}`,
            method: 'GET',
            success: (response) => {
                if (response.success) {
                    // 创建模态框
                    const modal = $(`
                        <div class="modal fade" id="shareModal" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title">分享文件</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="mb-3">
                                            <label class="form-label">文件名</label>
                                            <input type="text" class="form-control" value="${filename}" readonly>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">分享链接</label>
                                            <div class="input-group">
                                                <input type="text" class="form-control" value="${response.url}" readonly>
                                                <button class="btn btn-outline-secondary" type="button" onclick="copyToClipboard(this)">
                                                    复制
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `);

                    // 显示模态框
                    modal.modal('show');
                    
                    // 模态框关闭时移除
                    modal.on('hidden.bs.modal', function () {
                        $(this).remove();
                    });
                } else {
                    showError('生成分享链接失败');
                }
            },
            error: () => {
                showError('网络错误，请重试');
            }
        });
    }

    copyToClipboard(button) {
        const input = $(button).closest('.input-group').find('input');
        input.select();
        document.execCommand('copy');
        showSuccess('链接已复制到剪贴板');
    }
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 工具函数
function showLoading() {
    $('#loadingSpinner').show();
}

function hideLoading() {
    $('#loadingSpinner').hide();
}

function showError(message) {
    $.toast({
        text: message,
        icon: 'error',
        position: 'top-center'
    });
}

function showSuccess(message) {
    $.toast({
        text: message,
        icon: 'success',
        position: 'top-center'
    });
}

// 初始化文件列表管理器
const fileManager = new FileListManager();
$(document).ready(() => fileManager.loadFiles()); 